#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "InetAddr.hpp"


using namespace LogModule;

using func_t = std::function<void(int, const std::string&, InetAddr&)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
        :_socketfd(-1), _port(port), _isrunning(false), _func(func)
    {}

    void Init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socketfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket success, socketfd: " << _socketfd;

        // 填充sockaddr_in结构体
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        // 绑定IPv4地址结构
        int n = bind(_socketfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd : " << _socketfd;
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_socketfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                // 服务端需要知道客户端的ip和端口号
                InetAddr client(peer);

                buffer[n] = 0;

                // 回调进行路由转发、
                _func(_socketfd, buffer, client);
            }
        }
    }

    ~UdpServer() {}
private:
    int _socketfd;
    uint16_t _port; // 端口号
    bool _isrunning;

    func_t _func;
};
